package com.cskaoyan.service;

import com.cskaoyan.bean.bo.CartAddBO;
import com.cskaoyan.bean.bo.WxCartCheckedBO;
import com.cskaoyan.bean.bo.WxCartDeleteBO;
import com.cskaoyan.bean.bo.WxCartUpdateBO;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.vo.wx_cart.*;
import com.cskaoyan.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: Ryan
 * @CreateTime: 2022-09-08  17:45
 */
@Service
public class WxCartServiceImpl implements WxCartService{
    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketSystemMapper marketSystemMapper;

    @Override
    public WxCartIndexVO queryCartIndex() {

        //只查询deleted为0即false的信息 也就是未被删除
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andDeletedEqualTo(false);

        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);

        WxCartIndexVO wxCartIndexVO = new WxCartIndexVO();

        LinkedList<WxCartIndexListVO> cartIndexListVOS = new LinkedList<>();

        //计算cartTotal表中的数据
        short goodsCount = 0;
        short checkedGoodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        BigDecimal checkedGoodsAmount=new BigDecimal(0);
        for (MarketCart marketCart : marketCarts) {
            goodsCount = (short)(goodsCount + marketCart.getNumber());
            if (marketCart.getChecked()){
                checkedGoodsCount = (short)(checkedGoodsCount + marketCart.getNumber());
                checkedGoodsAmount = BigDecimal.valueOf(checkedGoodsAmount.doubleValue()+(marketCart.getPrice().doubleValue() * marketCart.getNumber().doubleValue()));
            }
            goodsAmount = BigDecimal.valueOf(goodsAmount.doubleValue()+(marketCart.getPrice().doubleValue() * marketCart.getNumber().doubleValue()));

            WxCartIndexListVO wxCartIndexListVO = new WxCartIndexListVO();
            BeanUtils.copyProperties(marketCart,wxCartIndexListVO);
            cartIndexListVOS.add(wxCartIndexListVO);
        }
        CartTotal cartTotal = new CartTotal(goodsCount,checkedGoodsCount,goodsAmount,checkedGoodsAmount);
        wxCartIndexVO.setCartTotal(cartTotal);
        wxCartIndexVO.setCartList(cartIndexListVOS);

        return wxCartIndexVO;
    }

    @Override
    public WxCartCheckoutVO queryCartCheckout(Integer cartId, Integer addressId, Integer couponId, Integer userCouponId, Integer grouponRulesId,MarketUser user) {
        //总表
        WxCartCheckoutVO wxCartCheckoutVO = new WxCartCheckoutVO();

        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();

        //通过userId在cart表中获取checked为1且未被删除的的商品表
        Integer userId = user.getId();

        criteria.andCheckedEqualTo(true);
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);

        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);

        //goodsTotalPrice购物车总价格
        BigDecimal goodsTotalPrice = new BigDecimal(0);
        //goodsList子表
        LinkedList<WxCartCheckoutGoodListVO> goodListVOS = new LinkedList<>();
        for (MarketCart marketCart : marketCarts) {
            Double number = marketCart.getNumber().doubleValue();
            Double price = marketCart.getPrice().doubleValue();

            goodsTotalPrice = BigDecimal.valueOf(goodsTotalPrice.doubleValue() + (price * number));

            WxCartCheckoutGoodListVO checkoutGoodVO = new WxCartCheckoutGoodListVO();
            BeanUtils.copyProperties(marketCart,checkoutGoodVO);
            goodListVOS.add(checkoutGoodVO);
        }
        wxCartCheckoutVO.setCheckedGoodsList(goodListVOS);

        //addressVO
        WxCartCheckoutAddressVO addressVO = new WxCartCheckoutAddressVO();

        MarketAddress marketAddress = new MarketAddress();
        if (addressId != 0) {
            marketAddress = marketAddressMapper.selectByPrimaryKey(addressId);
        }else if (addressId == 0){
            //查找对应userId的address信息 且优先查找default 为true 即是默认地址信息
            MarketAddressExample marketAddressExample = new MarketAddressExample();
            MarketAddressExample.Criteria criteria1 = marketAddressExample.createCriteria();
            criteria1.andUserIdEqualTo(userId).andIsDefaultEqualTo(true);

            List<MarketAddress> marketAddressList = marketAddressMapper.selectByExample(marketAddressExample);
            marketAddress = marketAddressList.get(0);
        }
        BeanUtils.copyProperties(marketAddress,addressVO);
        // addressVO.setAddTime(new Date(System.currentTimeMillis()));
        // addressVO.setUpdateTime(new Date(System.currentTimeMillis()));
        wxCartCheckoutVO.setCheckedAddress(addressVO);


        //通过ID查找优惠券表
        BigDecimal discount = new BigDecimal(0);
        MarketCoupon marketCoupon = new MarketCoupon();
        Short couponLength = 0;
        if (couponId != 0 && couponId != -1) {
            marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
            discount = marketCoupon.getDiscount();
            couponLength = marketCoupon.getDays();
        }else if (couponId == 0){
            discount = BigDecimal.valueOf(0);
        }



        //计算运费freightPrice
        //免运费的最小值
        MarketSystem marketSystem = marketSystemMapper.selectByPrimaryKey(6);
        String freightMin = marketSystem.getKeyValue();

        //运费价钱
        MarketSystem marketSystem1 = marketSystemMapper.selectByPrimaryKey(8);
        String freight = marketSystem1.getKeyValue();

        Double freightPrice = 0.00;
        if (goodsTotalPrice.doubleValue() < Double.valueOf(freightMin)){
            freightPrice = Double.valueOf(freight);
        }

        //计算得到actualPrice
        BigDecimal actualPrice = new BigDecimal(0);
        actualPrice =BigDecimal.valueOf(goodsTotalPrice.doubleValue() - discount.doubleValue() + freightPrice);


        //总表
        wxCartCheckoutVO.setGrouponRulesId(grouponRulesId);
        wxCartCheckoutVO.setActualPrice(actualPrice);
        wxCartCheckoutVO.setOrderTotalPrice(actualPrice);
        wxCartCheckoutVO.setCartId(cartId);
        wxCartCheckoutVO.setUserCouponId(userCouponId);
        wxCartCheckoutVO.setCouponId(couponId);
        wxCartCheckoutVO.setGoodsTotalPrice(goodsTotalPrice);
        wxCartCheckoutVO.setAddressId(addressId);
        wxCartCheckoutVO.setGrouponPrice(0);
        wxCartCheckoutVO.setCouponPrice(discount);
        wxCartCheckoutVO.setAvailableCouponLength(couponLength);
        wxCartCheckoutVO.setFreightPrice(freightPrice.toString());
        return wxCartCheckoutVO;
    }

    @Override
    public WxCartIndexVO cartChecked(WxCartCheckedBO wxCartCheckedBO) {
        //所需要传值的内容
        CartTotal cartTotal = new CartTotal();
        List<WxCartIndexListVO> cartIndexListVOS = new LinkedList<>();

        //先对cartList传值 并在循环中计算cartTotal中的值
        //通过productId更改chart表中checked状态： ‘1’ 表示true 即✔的
        List<Integer> productIds = wxCartCheckedBO.getProductIds();
        Boolean isChecked = wxCartCheckedBO.getIsChecked();

        MarketCart cart = new MarketCart();
        cart.setChecked(isChecked);

        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andProductIdIn(productIds);

        marketCartMapper.updateByExampleSelective(cart, marketCartExample);


        //通过查询cart表对✔的数据进行统计
        MarketCartExample marketCartExample1 = new MarketCartExample();
        marketCartExample1.createCriteria().andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample1);
        //计算cartTotal表中的数据
        short goodsCount = 0;
        short checkedGoodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        BigDecimal checkedGoodsAmount=new BigDecimal(0);
        for (MarketCart marketCart : marketCarts) {
            goodsCount = (short)(goodsCount + marketCart.getNumber());
            if (marketCart.getChecked()){
                checkedGoodsCount = (short)(checkedGoodsCount + marketCart.getNumber());
                checkedGoodsAmount = BigDecimal.valueOf(checkedGoodsAmount.doubleValue()+(marketCart.getPrice().doubleValue() * marketCart.getNumber().doubleValue()));
            }
            goodsAmount = BigDecimal.valueOf(goodsAmount.doubleValue()+(marketCart.getPrice().doubleValue() * marketCart.getNumber().doubleValue()));

            WxCartIndexListVO wxCartIndexListVO = new WxCartIndexListVO();
            BeanUtils.copyProperties(marketCart,wxCartIndexListVO);
            cartIndexListVOS.add(wxCartIndexListVO);
        }
        cartTotal = new CartTotal(goodsCount,checkedGoodsCount,goodsAmount,checkedGoodsAmount);


        return new WxCartIndexVO(cartTotal,cartIndexListVOS);
    }

    @Override
    public void cartUpdate(WxCartUpdateBO wxCartUpdateBO) {

        Integer cartId = wxCartUpdateBO.getId();
        Short number = wxCartUpdateBO.getNumber();
        //通过cartId更改表中的数量
        MarketCart marketCart = new MarketCart();
        marketCart.setNumber(number);

        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andIdEqualTo(cartId);

        marketCartMapper.updateByExampleSelective(marketCart,marketCartExample);
    }

    @Override
    public WxCartIndexVO cartdelete(WxCartDeleteBO wxCartDeleteBO) {
        //通过productIds删除掉购物车中 也就是更新deleted为1
        List<Integer> productIds = wxCartDeleteBO.getProductIds();
            MarketCart marketCart1 = new MarketCart();
            marketCart1.setDeleted(true);

            MarketCartExample marketCartExample = new MarketCartExample();
            marketCartExample.createCriteria().andProductIdIn(productIds);

            marketCartMapper.updateByExampleSelective(marketCart1,marketCartExample);

        //生成响应报文------------------------------------------------------------
        CartTotal cartTotal = new CartTotal();
        List<WxCartIndexListVO> cartIndexListVOS = new LinkedList<>();

        MarketCartExample marketCartExample1 = new MarketCartExample();
        marketCartExample1.createCriteria().andDeletedEqualTo(false);
        //通过查询cart表对✔的数据进行统计
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample1);
        //计算cartTotal表中的数据
        short goodsCount = 0;
        short checkedGoodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        BigDecimal checkedGoodsAmount=new BigDecimal(0);
        for (MarketCart marketCart : marketCarts) {
            goodsCount = (short)(goodsCount + marketCart.getNumber());
            if (marketCart.getChecked()){
                checkedGoodsCount = (short)(checkedGoodsCount + marketCart.getNumber());
                checkedGoodsAmount = BigDecimal.valueOf(checkedGoodsAmount.doubleValue()+(marketCart.getPrice().doubleValue() * marketCart.getNumber().doubleValue()));
            }
            goodsAmount = BigDecimal.valueOf(goodsAmount.doubleValue()+(marketCart.getPrice().doubleValue() * marketCart.getNumber().doubleValue()));

            WxCartIndexListVO wxCartIndexListVO = new WxCartIndexListVO();
            BeanUtils.copyProperties(marketCart,wxCartIndexListVO);
            cartIndexListVOS.add(wxCartIndexListVO);
        }
        cartTotal = new CartTotal(goodsCount,checkedGoodsCount,goodsAmount,checkedGoodsAmount);


        return new WxCartIndexVO(cartTotal,cartIndexListVOS);
    }

    @Override
    public Integer cartSelectGoodscount() {
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andDeletedEqualTo(false);

        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        Integer count = 0;
        for (MarketCart marketCart : marketCarts) {
            count += marketCart.getNumber();
        }
        return count;
    }

    @Override
    public Integer cartAdd(CartAddBO cartAddBO,MarketUser user) {
        Short addNumber = cartAddBO.getNumber().shortValue();
        Integer productId = cartAddBO.getProductId();
        Integer goodsId = cartAddBO.getGoodsId();
        //通过productId查询表获得
        MarketGoodsProduct goodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);

        MarketCart marketCart = new MarketCart();
        marketCart.setUserId(user.getId());
        marketCart.setGoodsId(goodsId);
        marketCart.setGoodsSn(goodsId.toString());
        marketCart.setProductId(productId);
        marketCart.setPicUrl(marketGoods.getPicUrl());//通过goodsId获得
        marketCart.setGoodsName(marketGoods.getName());//通过goodsId查表获得
        marketCart.setSpecifications(goodsProduct.getSpecifications());
        marketCart.setPrice(goodsProduct.getPrice());
        marketCart.setNumber(addNumber);
        marketCart.setAddTime(new Date(System.currentTimeMillis()));
        marketCart.setUpdateTime(new Date(System.currentTimeMillis()));

        //把po插入cart表中
        marketCartMapper.insertSelective(marketCart);
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andDeletedEqualTo(false);

        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        Integer count = 0;
        for (MarketCart marketCart1 : marketCarts) {
            count += marketCart1.getNumber();
        }
        return count;
    }

    @Override
    public Integer cartFastadd(CartAddBO cartAddBO, MarketUser user) {
        Short addNumber = cartAddBO.getNumber().shortValue();
        Integer productId = cartAddBO.getProductId();
        Integer goodsId = cartAddBO.getGoodsId();
        //通过productId查询表获得
        MarketGoodsProduct goodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);

        MarketCart marketCart = new MarketCart();
        marketCart.setUserId(user.getId());
        marketCart.setGoodsId(goodsId);
        marketCart.setGoodsSn(goodsId.toString());
        marketCart.setProductId(productId);
        marketCart.setPicUrl(marketGoods.getPicUrl());//通过goodsId获得
        marketCart.setGoodsName(marketGoods.getName());//通过goodsId查表获得
        marketCart.setSpecifications(goodsProduct.getSpecifications());
        marketCart.setPrice(goodsProduct.getPrice());
        marketCart.setNumber(addNumber);
        marketCart.setAddTime(new Date(System.currentTimeMillis()));
        marketCart.setUpdateTime(new Date(System.currentTimeMillis()));

        //把po插入cart表中
        marketCartMapper.insertSelective(marketCart);
        Integer cartId = marketCart.getId();

        return cartId;
    }
}
